<script>
import { LoadingControl } from "./utils";
export default {
  name: "StatusHandle",
  props: {
    status: String,
    get: {
      type: Function,
    },
    loading: {
      type: Object,
      default() {
        return {
          type: "normal",
          color: "#000",
          size: 25,
        };
      },
    },
    block: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      inner: {
        status: "",
        error: "",
      },
    };
  },
  created() {
    if (this.status) {
      this.inner.status = this.status;
    }
    this.getData();
  },
  watch: {
    status(v) {
      this.inner.status = v;
    },
  },
  methods: {
    refresh(params) {
      this.getData(params)
    },
    getData(params) {
      const { inner, get } = this;
      if (get) {
        LoadingControl({
          call: get,
          params,
          change: ({ status }) => {
            this.inner.status = status;
          },
        }).catch((e) => {
          this.inner.error = typeof e === "object" ? e.message : e;
        });
      } else {
        this.$nextTick(() => {
          if (!["loading", "success"].includes(inner.status)) {
            this.$emit("retry");
          }
        });
      }
    },
    getLoading() {
      const { $slots, loading } = this;
      return (
        $slots.loading || (
          <van-loading color={loading.color} size={loading.size + "px"} />
        )
      );
    },
  },
  render() {
    const { inner, block } = this;
    switch (inner.status) {
      case "":
      case "init":
      case "loading":
        return (
          <div
            class={[
              "loading-box flex-column",
              inner.status,
              block ? "block align " : "",
            ]}
          >
            {this.getLoading()}
          </div>
        );
      case "success":
        return this.$slots ? this.$slots.default : null;
      case "error":
      default:
        if (block) {
          return (
            <button
              class={["retry block", inner.status]}
              onClick={this.getData}
            >
              <van-empty image="error" description={inner.error} />
            </button>
          );
        } else {
          return (
            <button class="retry" onClick={this.getData}>
              {inner.error}
              {inner.error ? "," : ""}点我重试
            </button>
          );
        }
    }
  },
};
</script>
<style lang="scss">
.loading-box {
  &.block {
    padding: 15px;
    width: 100%;
  }
}
.retry {
  margin: 0;
  padding: 0;
  font-size: 14px;
  line-height: 25px;
  text-align: center;
  cursor: pointer;
  &.block {
    padding: 15px;
    width: 100%;
  }
}
</style>
